import 'package:flutter/material.dart';
import '../models/heritage_activity.dart';

// 活动状态管理
class ActivityProvider extends ChangeNotifier {
  List<HeritageActivity> _activities = [];
  List<HeritageActivity> _filteredActivities = [];
  String _selectedCategory = 'all';
  String _searchQuery = '';
  bool _isLoading = false;
  String? _error;
  
  // 用户相关数据
  List<String> _favoriteActivityIds = [];
  List<String> _registeredActivityIds = [];
  Map<String, Map<String, dynamic>> _userParticipation = {};

  // Getters
  List<HeritageActivity> get activities => _activities;
  List<HeritageActivity> get filteredActivities => _filteredActivities;
  String get selectedCategory => _selectedCategory;
  String get searchQuery => _searchQuery;
  bool get isLoading => _isLoading;
  String? get error => _error;
  List<String> get favoriteActivityIds => _favoriteActivityIds;
  List<String> get registeredActivityIds => _registeredActivityIds;
  Map<String, Map<String, dynamic>> get userParticipation => _userParticipation;

  ActivityProvider() {
    _loadInitialData();
  }

  void _loadInitialData() {
    _isLoading = true;
    notifyListeners();

    // 模拟加载数据
    Future.delayed(const Duration(milliseconds: 500), () {
      _activities = _generateMockActivities();
      _filteredActivities = List.from(_activities);
      _loadUserData();
      _isLoading = false;
      notifyListeners();
    });
  }

  List<HeritageActivity> _generateMockActivities() {
    return [
      HeritageActivity(
        id: '1',
        title: '传统书法体验课',
        description: '学习传统书法技艺，感受中华文化的博大精深。',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20calligraphy%20class&image_size=landscape_4_3',
        location: '文化中心书法室',
        startDate: DateTime.now().add(const Duration(days: 3)),
        endDate: DateTime.now().add(const Duration(days: 3, hours: 2)),
        maxParticipants: 20,
        currentParticipants: 15,
        price: 0,
        category: 'education',
        tags: ['书法', '传统文化'],
        organizer: '市文化协会',
        contactInfo: '联系电话：123-456-7890',
        status: ActivityStatus.upcoming,
        requirements: '无特殊要求',
        highlights: ['专业指导', '免费参与'],
        rating: 4.8,
        reviewCount: 25,
        isFeatured: true,
        isRecommended: true,
        createdAt: DateTime.now().subtract(const Duration(days: 10)),
        updatedAt: DateTime.now().subtract(const Duration(days: 1)),
      ),
      HeritageActivity(
        id: '2',
        title: '陶艺制作工坊',
        description: '亲手制作传统陶器，体验泥土与火的艺术。',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=pottery%20making%20workshop&image_size=landscape_4_3',
        location: '艺术工作室',
        startDate: DateTime.now().add(const Duration(days: 7)),
        endDate: DateTime.now().add(const Duration(days: 7, hours: 3)),
        maxParticipants: 15,
        currentParticipants: 8,
        price: 80,
        category: 'craft',
        tags: ['陶艺', '手工制作'],
        organizer: '陶艺大师工作室',
        contactInfo: '联系电话：123-456-7891',
        status: ActivityStatus.upcoming,
        requirements: '请穿着便于活动的服装',
        highlights: ['专业指导', '材料提供'],
        rating: 4.6,
        reviewCount: 18,
        isFeatured: false,
        isRecommended: true,
        createdAt: DateTime.now().subtract(const Duration(days: 8)),
        updatedAt: DateTime.now().subtract(const Duration(days: 2)),
      ),
    ];
  }

  void _loadUserData() {
    _favoriteActivityIds = ['1'];
    _registeredActivityIds = ['1'];
    _userParticipation = {
      '1': {
        'status': 'registered',
        'registrationDate': DateTime.now().subtract(const Duration(days: 2)),
        'paymentStatus': 'completed',
      },
    };
  }

  // 搜索和筛选
  void setSearchQuery(String query) {
    _searchQuery = query;
    _applyFilters();
  }

  void setCategory(String category) {
    _selectedCategory = category;
    _applyFilters();
  }

  void _applyFilters() {
    _filteredActivities = _activities.where((activity) {
      final matchesCategory = _selectedCategory == 'all' || activity.category == _selectedCategory;
      final matchesSearch = _searchQuery.isEmpty ||
          activity.title.toLowerCase().contains(_searchQuery.toLowerCase()) ||
          activity.description.toLowerCase().contains(_searchQuery.toLowerCase());
      return matchesCategory && matchesSearch;
    }).toList();
    notifyListeners();
  }

  // 活动操作
  Future<bool> registerForActivity(String activityId, Map<String, dynamic> registrationData) async {
    try {
      _isLoading = true;
      notifyListeners();

      await Future.delayed(const Duration(seconds: 1));

      final activityIndex = _activities.indexWhere((a) => a.id == activityId);
      if (activityIndex != -1) {
        _activities[activityIndex] = _activities[activityIndex].copyWith(
          currentParticipants: _activities[activityIndex].currentParticipants + 1,
        );
      }

      _registeredActivityIds.add(activityId);
      _userParticipation[activityId] = {
        'status': 'registered',
        'registrationDate': DateTime.now(),
        'paymentStatus': 'completed',
        'registrationData': registrationData,
      };

      _applyFilters();
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _error = '报名失败: $e';
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }

  void toggleFavorite(String activityId) {
    if (_favoriteActivityIds.contains(activityId)) {
      _favoriteActivityIds.remove(activityId);
    } else {
      _favoriteActivityIds.add(activityId);
    }
    notifyListeners();
  }

  bool isFavorite(String activityId) {
    return _favoriteActivityIds.contains(activityId);
  }

  bool isRegistered(String activityId) {
    return _registeredActivityIds.contains(activityId);
  }

  HeritageActivity? getActivityById(String id) {
    try {
      return _activities.firstWhere((activity) => activity.id == id);
    } catch (e) {
      return null;
    }
  }

  List<HeritageActivity> getRecommendedActivities({int limit = 5}) {
    return _activities.where((activity) => activity.isRecommended).take(limit).toList();
  }

  Map<String, dynamic> getUserStats() {
    return {
      'totalActivities': _registeredActivityIds.length,
      'completedActivities': 0,
      'favoriteActivities': _favoriteActivityIds.length,
      'totalHours': 0,
      'points': 0,
    };
  }

  Future<void> refresh() async {
    _error = null;
    _loadInitialData();
  }

  void clearError() {
    _error = null;
    notifyListeners();
  }
}